package com.hiray.wanandroid.data

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.hiray.wanandroid.net.ApiHelper
import com.hiray.wanandroid.net.response.HomeFeed

class SquareFeedSource : PagingSource<Int, HomeFeed>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, HomeFeed> {
        val page = params.key ?: 0
        val prevKey = if (page == 0) null else page - 1

        val res = ApiHelper.api().fetchSquareFeed(page = page)
        return if (res.isSuccess) {
            LoadResult.Page(
                res.items,
                prevKey,
                page + 1
            )
        } else {
            LoadResult.Error(Throwable(res.errMsg))
        }
    }

    override fun getRefreshKey(state: PagingState<Int, HomeFeed>): Int {
        return 1
    }
}